package com.telit.dispose.service.resourceManagement.impl;

import com.telit.common.enums.ResultCode;
import com.telit.common.exception.ForestBaseException;
import com.telit.dispose.dao.resourceManagement.DictMapper;
import com.telit.dispose.entity.resourceManagement.Dict;
import com.telit.dispose.service.resourceManagement.DictService;
import com.telit.dispose.vo.resourceManagement.DictVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


/**
 * Create by Chencf 2022/09/05
 */
@Service
public class DictServiceImpl implements DictService {

    @Autowired
    private DictMapper dictMapper;


    /**
     * 根据父节点code，获取字典列表
     */
    @Override
//    @BaseCache(params = {"#code"})
    public List<DictVO> listByParentCode(String code) {
        if (code == null) {
            return new ArrayList<>();
        }
        List<DictVO> list = dictMapper.listByParentCode(code);
        if (list == null) {
            return new ArrayList<>();
        }
        return list;
    }

    //添加字典父节点  新添加字典需要将原来的缓存删除
    @Override
    @Transactional
//    @BaseCache(type = CacheType.delete)
    public void insert(Dict dict) {
        if (dict.getParentId() == null) {
            dict.setParentId(0L);
        }
        // 根据parentId 和 configCode 校验数据的唯一
        Dict existConfigCode = dictMapper.simpleGetByPidAndCode(dict.getParentId(), dict.getConfigCode());
        if (existConfigCode != null) {
            throw new ForestBaseException(ResultCode.RECORD_EXIST.getCode(), "字典编码已存在!");
        }
        dictMapper.insert(dict);
    }

    @Override
    @Transactional
//    @BaseCache(type = CacheType.delete)
    public void deleteDictById(Long id) {
        dictMapper.deleteById(id);
    }

    @Override
    public Dict selectByDictId(Long id) {
        return dictMapper.selectById(id);
    }

    /**
     * 根据父节点id，获取字典列表
     */
    @Override
//    @BaseCache(params = {"#parentId"})
    public List<Dict> findByParentId(Integer parentId) {
        if (parentId == null) {
            return new ArrayList<>();
        }
        return dictMapper.findByParentId(parentId);
    }

    @Override
    public DictVO findDictInfoByCode(String parentCode, String childCode) {
        DictVO dictInfoByCode = dictMapper.findDictInfoByCode(parentCode, childCode);
        return dictInfoByCode;
    }

}
